package com.lagou.client;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;

import java.util.List;
import java.util.concurrent.ExecutorService;

/**
 * 基于ZkClient 子节点监听器
 */
public class LagouZkChildListener implements IZkChildListener {
    private List<String> servers;
    private ZkClient zkClient;
    private ExecutorService executor;
    private String parentNode;

    public LagouZkChildListener(List<String> servers, ZkClient zkClient, ExecutorService executor, String parentNode) {
        this.servers = servers;
        this.zkClient = zkClient;
        this.executor = executor;
        this.parentNode = parentNode;
    }

    public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
        //如果之前的子节点数少于当前的的子节点数，服务器上线
        if(servers.size()< currentChilds.size()){
            //获取新增的子节点
            for (String currentChild : currentChilds) {
                if(!servers.contains(currentChild)){
                    String data = zkClient.readData(parentNode + "/" + currentChild);
                    System.out.println("服务端 "+data+" 上线");
                    ClientBootStrap.startClientByZkNode(zkClient,executor,parentNode,currentChild);
                }
            }
        }
        //将本次子节点存储，供下次对比
        servers=currentChilds;
    }
}
